import {
  View,
  ActivityIndicator,
  FlatList,
  Image,
  SafeAreaView,
} from 'react-native';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import { useNavigation } from '@react-navigation/native';

import {MovieCell, MovieCellProps} from '../../components/MovieCell';
import BottomMenu from '../../components/BottomMenu';
import Icon from 'react-native-vector-icons/FontAwesome5';
import SearchModal from '../../components/SearchModal';
import {storeSearchHistory} from '../../utils/storageUtils'
const HomeScreen = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState<MovieCellProps[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [isEnd, setIsEnd] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [searchModalVisible, setSearchModalVisible] = useState(false);
  const navigation = useNavigation();

  let canLoadMore = true;
  useEffect(() => {
    storeSearchHistory()
  }, [])
  
  useEffect(() => {
    setLoading(true);
    getMovies();
  }, [currentPage]);
  const getMovies = useCallback(() => {
    fetch(`http://192.168.0.106:3008/movies/${currentPage}`)
      .then(response => response.json())
      .then(json => {
        setLoading(false);
        if (json?.length !== 0) {
          setData(data.concat(json));
          setLoading(false);
        } else {
          setIsEnd(true);
        }
      })
      .catch(error => {
        setLoading(false);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [currentPage]);

  const handleLoadMore = () => {
    setTimeout(() => {
      if (canLoadMore && !isEnd) {
        setCurrentPage(currentPage + 1);
        canLoadMore = false;
      }
    }, 100);

    //}
  };
  const renderHeader = () => {
    return isLoading ? (
      <View style={{marginTop: 10, alignItems: 'center'}}>
        <ActivityIndicator size={'large'} />
      </View>
    ) : (
      <View>
        <Icon.Button
          color={'white'}
          size={10}
          name="search"
          onPress={toggleSearchModal}
          backgroundColor="transparent"
        />
      </View>
    );
  };
  const renderFooter = () => {
    return isLoading ? (
      <View style={{marginTop: 10, alignItems: 'center'}}>
        <ActivityIndicator size={'large'} />
      </View>
    ) : null;
  };

  const toggleBottomSheet = () => {
    setModalVisible(!modalVisible);
  };
  const toggleSearchModal = () => {
    setSearchModalVisible(!searchModalVisible);
  };

  return (
    <SafeAreaView style={{backgroundColor: 'black', flex: 1}}>
      <FlatList
        style={{flex: 1}}
        data={data}
        keyExtractor={(item, index) =>
          item.title.toString() + item.cover.toString()
        }
        renderItem={({item}) => (
          <MovieCell {...item} onClickMore={toggleBottomSheet} goDetail={() => navigation.navigate('Detail')} />
        )}
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0}
        ListHeaderComponent={renderHeader}
        ListFooterComponent={renderFooter}
        onMomentumScrollBegin={() => (canLoadMore = true)}
      />

      <BottomMenu
        modalVisible={modalVisible}
        onClickClose={toggleBottomSheet}
      />

      <SearchModal
        modalVisible={searchModalVisible}
        onClickClose={toggleSearchModal}
      />
    </SafeAreaView>
  );
};

export default HomeScreen;
